package yxy.game.pm2.command.yilingbattle;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.YiLingMessage;
import yxy.game.pm2.module.yiling.YiLingBattleHandle;
import yxy.game.pm2.module.yiling.YiLingBattleModule;

/****************************************
 * @name CMD_YiLingBattleEnemy
 * @description 夷陵之战 挑战前置准备
 * @author 梁健彬
 * @since 2022-05-17
 ***************************************/
@MessageType(proto = Command.YiLingBattleEnemy, classtype = YiLingMessage.YiLingBattleEnemyRequest.class)
public class CMD_YiLingBattleEnemy extends Command<YiLingMessage.YiLingBattleEnemyRequest> {

    @Override
    public void execute(MessageSource messageSource, YiLingMessage.YiLingBattleEnemyRequest request) {

        YiLingMessage.YiLingBattleEnemyResponse.Builder response = YiLingMessage.YiLingBattleEnemyResponse.newBuilder();
        try {
            String playerCode = messageSource.getTag();
            YiLingBattleHandle handle = new YiLingBattleHandle();
            YiLingBattleModule module = YiLingBattleModule.get(playerCode);

            if (handle.isBattling(playerCode)) {
                send(messageSource, response, Result.BattleIsRunning);// 还有正在进行中的战斗
                return;
            }

            if (module.getMaxCustomsPass() >= YiLingBattleHandle.maxChallengeTimes){
                send(messageSource, response, Result.YiLingBattleCanChallenge);// 今日挑战次数达到上限
                return;
            }

            //battle前置准备  生成battle缓存
            response.setBattle(handle.battleResponse(playerCode));
            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }


    }

    private void send(MessageSource messageSource, YiLingMessage.YiLingBattleEnemyResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}